<template>
  <el-dialog v-model="dialogVisible" :title="title" width="800" :before-close="handleClose">
    <div class="main">
      <el-form :model="model" label-width="110px" ref="formRef" label-position="top">
        <div v-for="(item, index) in info" :key="index">
          <el-form-item :label="dict_format(item)" v-if="item.fieldName=='enterprise'" :prop="item.fieldName">
            <div class="flex alignCenter" style="width: 100%">
              <el-select @change="handleChange" v-model="model[item.fieldName]" filterable remote reserve-keyword :placeholder="`请选择${dict_format(item)}`" :remote-method="remoteMethod" :loading="loading">
                <el-option v-for="(item,index) in enterpriseList" :key="index" :label="item.qymc" :value="item.qymc" />
              </el-select>
              <el-button type="primary" icon="CopyDocument" @click="proxy.$utils.copy(model[item.fieldName])" />
            </div>
          </el-form-item>
          <!-- 输入框 -->
          <el-form-item :label="dict_format(item)" v-else-if="item.type=='input'" :prop="item.fieldName">
            <div class="flex width100" v-if="item.fieldName=='enterpriseJurisdiction'">
              <el-input v-model="model.city" placeholder="请输入xx市">
                <template #append>市</template>
              </el-input>
              <el-input v-model="model.district" placeholder="请输入xx区" style="margin-left: 10px;">
                <template #append>区</template>
              </el-input>
            </div>
            <el-input v-else v-model="model[item.fieldName]" :placeholder="`请输入${dict_format(item)}`" clearable />
          </el-form-item>
          <!-- 下拉选择 -->
          <el-form-item :label="dict_format(item)" v-else-if="item.type=='select'" :prop="item.fieldName">
            <el-select v-model="model[item.fieldName]" :placeholder="`请选择${dict_format(item)}`">
              <el-option v-for="(item,index) in options(item)" :key="index" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <!-- 上传图片 -->
          <el-form-item :label="dict_format(item)" v-else-if="item.type=='image'" :prop="item.fieldName">
            <uploadImage v-model="model[item.fieldName]" :limit="9"></uploadImage>
          </el-form-item>
          <!-- 关联性 -->
          <el-form-item :label="dict_format(item)" v-else-if="item.type=='relation'" :prop="item.fieldName">
            <el-select popper-class="relationSelect" v-model="model[item.fieldName]" :placeholder="`请选择${dict_format(item)}`" @change="relationChange(model[item.fieldName],proxy.$utils.transformArray(item.defaultValueTableChildren,'id','parentId'))">
              <el-option v-for="(item,index) in proxy.$utils.transformArray(item.defaultValueTableChildren,'id','parentId')" :key="index" :value="item.title">
                <div>{{item.title}}</div>
                <div v-html="item.intro"></div>
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 单选框 -->
          <el-form-item :label="dict_format(item)" v-else-if="item.type=='radio'" :prop="item.fieldName">
            <el-radio-group v-model="model[item.fieldName]">
              <el-radio :value="item.title" v-for="(item,index) in item.defaultValueTable" :key="index">{{item.title}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 复选框 -->
          <el-form-item :label="dict_format(item)" v-else-if="item.type=='checkbox'" :prop="item.fieldName">
            <el-checkbox-group v-model="model[item.fieldName]">
              <el-checkbox :label="item.title" :value="item.title" v-for="(item,index) in item.defaultValueTable" :key="index" />
            </el-checkbox-group>
          </el-form-item>
          <!-- 文件 -->
          <el-form-item :label="dict_format(item)" v-else-if="item.type=='file'" :prop="item.fieldName">
            <div>
              <el-button type="primary" @click="proxy.$refs[`templateFileRef${index}`][0].open()">上传附件</el-button>
              <FileUploader v-model="model[item.fieldName]" :ref="`templateFileRef${index}`"></FileUploader>
              <div v-if="model[item.fieldName]">
                <div v-if="proxy.$utils.isString(model[item.fieldName])">
                  <div v-for="(el,idx) in model[item.fieldName].split(',')" :key="idx">
                    <el-image :preview-src-list="previewList(model[item.fieldName].split(','))" style="width: 100px; height: 100px;margin-top:10px" :src="el.path?el.path:el" v-if="isImage(el)" />
                    <el-link :href="el" target="_blank">{{fileName(item.fieldName,model.name,idx)}}</el-link>
                  </div>
                </div>
                <div v-else-if="proxy.$utils.isArrayOrJsonArray(model[item.fieldName])">
                  <div v-for="(el,idx) in model[item.fieldName]" :key="idx">
                    <el-image :preview-src-list="previewList(model[item.fieldName])" style="width: 100px; height: 100px;margin-top:10px" :src="el.path?el.path:el" v-if="isImage(el)" />
                    <el-link :href="el.path?el.path:el" target="_blank" v-else>{{fileName(item.fieldName,model.name,idx)}}</el-link>
                  </div>
                </div>
              </div>
            </div>
          </el-form-item>
        </div>
        <!-- 报名所属 -->
        <!-- <el-form-item label="报名所属">
          <dictSelect v-model="model.affiliation" dictCode="registration_affiliation" multiple="1"></dictSelect>
        </el-form-item> -->
      </el-form>
      <!-- 关联性 -->
      <el-form v-if="relationList.length" label-width="110px" label-position="top">
        <el-form-item :label="item.title" v-for="(item,index) in relationList" :key="index">
          <div>
            <!-- <div v-html="item.intro"></div> -->
            <uploadImage v-model="item.value" v-if="item.type=='image'" :limit="9"></uploadImage>
            <div v-else-if="item.type=='file'">
              <el-button type="primary" @click="instance.refs[`fileRef${index}`][0].open()">上传附件</el-button>
              <FileUploader v-model="item.value" :ref="`fileRef${index}`"></FileUploader>
              <div v-if="item.value">
                <div v-if="proxy.$utils.isString(item.value)">
                  <div v-for="(el,idx) in item.value.split(',')" :key="idx">
                    <el-link :href="el" target="_blank">{{fileName(item.title,model.name,idx)}}</el-link>
                  </div>
                </div>
                <div v-else-if="proxy.$utils.isJsonArray(item.value)=='arr'">
                  <div v-for="(el,idx) in item.value" :key="idx">
                    <el-link :href="el" target="_blank">{{fileName(item.title,model.name,idx)}}</el-link>
                  </div>
                </div>
                <div v-else-if="proxy.$utils.isJsonArray(item.value)=='jsonArr'">
                  <div v-for="(el,idx) in item.value" :key="idx">
                    <el-link :href="el.path" target="_blank">{{fileName(item.title,model.name,idx)}}</el-link>
                  </div>
                </div>
              </div>
            </div>
            <div v-else-if="item.type=='templateFile'">
              <el-link :href="item.path" v-for="(item,index) in item.file" :key="index" style="margin-right: 20px;">{{item.name}}</el-link>
              <div @click="instance.refs[`templateFileRef2${index}`][0].open()" style="margin-top: 10px;">
                <el-button type="primary">上传附件</el-button>
              </div>
              <div v-for="(el,idx) in item.value" :key="idx">
                <el-link :href="el.path" target="_blank">{{fileName(item.title,model.name,idx)}}</el-link>
              </div>
              <FileUploader dataType="jsonArr" v-model="item.value" :ref="`templateFileRef2${index}`"></FileUploader>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <el-form v-if="ProofWork.length" label-width="110px" label-position="top">
        <el-form-item label="工作证明">
          <div v-for="(el,idx) in ProofWork" :key="idx">
            <el-image :preview-src-list="previewList(ProofWork)" style="width: 100px; height: 100px;margin-right:10px" :src="el.path?el.path:el" v-if="isImage(el)" />
            <el-link :href="el.path?el.path:el" target="_blank" v-else>{{fileName(item.fieldName,model.name,idx)}}</el-link>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submit">
          确 认
        </el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script setup lang="ts">
const emit = defineEmits(["fatherMethod"]);
import useCounterStore from "@/store/counter";
const counter = useCounterStore();
const instance = getCurrentInstance();
const { proxy } = getCurrentInstance();

const validateMobile = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error("请输入联系方式"));
  } else if (!proxy.$utils.isPoneAvailable(value)) {
    callback(new Error("请输入正确的联系方式"));
  } else {
    callback();
  }
};

const validateIdCard = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error("请输入身份证号"));
  } else if (!proxy.$utils.isIdCard(value)) {
    callback(new Error("请输入正确的身份证号"));
  } else {
    callback();
  }
};

let enterpriseList = ref([]); //企业列表
let loading = ref(false);
let model = ref({});
let dialogVisible = ref(false);
let info = ref({});
let dicts = ref([]);
let relationList = ref([]); //关联性
let ProofWork = ref([]); //工作证明
let curriculumData = {}; //课程详情
let orderId = ""; //订单id
let userId = ""; //用户id

let rules = ref({
  mobile: [{ required: true, validator: validateMobile, trigger: "blur" }],
  identityCard: [
    { required: true, validator: validateIdCard, trigger: "blur" },
  ],
  education: [{ required: true, message: "请输入学历", trigger: "blur" }],
  name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
  graduationMajor: [
    { required: true, message: "请输入毕业专业", trigger: "blur" },
  ],
  workYears: [
    { required: true, message: "请输入累计工作年限", trigger: "blur" },
  ],
  enterprise: [{ required: true, message: "请输入企业名称", trigger: "blur" }],
  conditions: [{ required: true, message: "请设置报名条件", trigger: "blur" }],
  enterpriseTax: [
    { required: true, message: "请设置所在企业税号", trigger: "blur" },
  ],
  enterpriseJurisdiction: [
    { required: true, message: "请设置所在企业区属", trigger: "blur" },
  ],
  identification_scancopy: [
    {
      required: true,
      message: "请上传您的《身份证》正反面扫描件",
      trigger: "blur",
    },
  ],
  certificate_scancopy: [
    {
      required: true,
      message: "请上传您的《毕业证书》扫描件",
      trigger: "blur",
    },
  ],
});

let title = computed(() => {
  return `报名资料修改 - ${model.value.name} - ${model.value.identityCard}`;
});

function previewList(array) {
  let arr = [];
  array.forEach((element) => {
    let a = element.path ? element.path : element;
    if (isImage(a)) arr.push(a);
  });
  return arr;
}

function isImage(el) {
  let a = el.path ? el.path : el;
  if (a.includes(".jpg") || a.includes(".png") || a.includes(".jpeg"))
    return true;
  return false;
}

function toHref(url) {
  window.location.href = url;
}

function fileName(fieldNamea, name, idx) {
  let modelArr = [
    {
      name: "身份证",
      value: "identification_scancopy",
    },
    {
      name: "毕业证书",
      value: "certificate_scancopy",
    },
  ];
  for (let index = 0; index < modelArr.length; index++) {
    const element = modelArr[index];
    if (element.value == fieldNamea) return `${name}_${element.name}${idx + 1}`;
  }
  return `${name}_${getFileName(fieldNamea)}${idx + 1}`;

  function getFileName(str) {
    let a = getBracketContents(str);
    if (a.length) return a[0];
    return str;
  }
  //获取书名号里面的值
  function getBracketContents(str) {
    // 正则表达式匹配书名号内的内容
    const regex = /《([^>]+)》/g;
    let match;
    let results = [];

    // 循环查找所有匹配项
    while ((match = regex.exec(str)) !== null) {
      results.push(match[1]); // 添加书名号内的内容到结果数组
    }

    return results; // 返回包含所有内容的数组
  }
}

let open = async (e, w, obj) => {
  orderId = obj.orderId;
  userId = obj.userId;
  curriculumData = proxy.$utils.deepcopy(e);
  if (e.needUserParams && e.needUserParams.length) {
    info.value = [...e.needUserParams];
    info.value.forEach((element) => {
      model.value[element.fieldName] = element.value;
    });
  }
  //工作证明
  if (w.ProofWork) ProofWork.value = w.ProofWork;

  model.value = { ...model.value, ...w.model }; //历史提交数据，当前课程需要的数据

  let { data } = await proxy.$apis.dict({
    type: "details",
    data: { code: "user_info" },
  });
  relationList.value = proxy.$utils.deepcopy(w.relationList);
  model.value = proxy.$utils.formatFunction(w.model, { ...model.value });
  //处理一层学员区属
  if (model.value.enterpriseJurisdiction && model.value.city) {
    model.value.enterpriseJurisdiction = `${model.value.city}${
      model.value.city.includes("市") ? "" : "市"
    }${model.value.district}${model.value.district.includes("区") ? "" : "区"}`;
  }
  if (!model.value.affiliation) model.value.affiliation = ""; //报名所属
  dicts.value = data;
  dialogVisible.value = true;
};

function relationChange(e, list) {
  let index = proxy.$utils.findIndexByField(list, "title", e);
  if (index != -1) relationList.value = [...list[index].children];
}

const remoteMethod = async (query: string) => {
  if (!query) return;
  try {
    loading.value = true;
    enterpriseList.value = await proxy.$apis.autoMatchCompany({
      key: query,
    });
  } catch (error) {
  } finally {
    loading.value = false;
  }
};

function handleChange(e) {
  let index = proxy.$utils.findIndexByField(enterpriseList.value, "qymc", e);
  if (index != -1) {
    // model.value.enterpriseInfo = enterpriseList.value[index];
    let info = enterpriseList.value[index];
    if (model.value.hasOwnProperty("enterpriseTax"))
      model.value.enterpriseTax = info.nsrsbh;
    //所属区属
    if (model.value.hasOwnProperty("enterpriseJurisdiction")) {
      let resp = extractAddressInfo(info.dzdh);
      model.value.enterpriseJurisdiction =
        resp.province + resp.city + resp.district;
    }
  }

  function extractAddressInfo(address) {
    const regex = /(.*省|.*自治区)?(.*市)?(.*区|.*县)?/;
    const matches = address.match(regex);
    if (address.includes("市") && address.includes("区")) {
      let province = matches[1] ? matches[1].trim() : "";
      let city = matches[2] ? matches[2].trim() : "";
      let district = matches[3] ? matches[3].trim() : "";

      return { province, city, district };
    } else {
      // 如果没有找到省市，返回第一个区之前的字符串
      const firstDistrictIndex = address.indexOf("区");
      if (firstDistrictIndex !== -1) {
        let aa = address.substring(0, firstDistrictIndex);
        return { province: "", city: "", district: aa + "区" };
      }
    }
  }
}

function options(params) {
  if (!params) return;
  return params.defaultValue.split(",");
}

function dict_format(params) {
  if (!dicts.value.length) return;
  let index = proxy.$utils.findIndexByField(
    dicts.value,
    "dict_code",
    params.fieldName
  );
  if (index != -1) return dicts.value[index].dict_label;
  console.log("字典未找到：" + params.fieldName);
}

async function save() {
  try {
    loading.value = true;
    if (relationList.value.length) {
      for (let index = 0; index < relationList.value.length; index++) {
        const element = relationList.value[index];
        if (element.hasOwnProperty("value")) {
          if (!element.value || !element.value.length)
            return proxy.$utils.showToast(element.title, 0);
        } else {
          return proxy.$utils.showToast(element.title, 0);
        }
      }
    }

    //提交信息
    let aa = { ...model.value };
    let userName = counter.ycAdminParams.userInfo.userInfo.userName;
    aa.updateUser = userName;
    aa["userId"] = userId;
    model.value["from"] = "web-order-info";
    await proxy.$apis.student({
      data: aa,
      type: "perfect",
    });

    await proxy.$apis.orderAction({
      type: "update",
      data: {
        approvalContent: {
          model: model.value,
          relationList: relationList.value,
        },
        updateUser: userName,
        orderId,
      },
    });
    proxy.$utils.showToast("修改成功");
    handleClose();
  } catch (error) {
    proxy.$utils.showToast(error, 0);
  } finally {
    loading.value = false;
  }
}

let submit = async () => {
  if (!proxy.$refs.formRef) return;
  proxy.$refs.formRef.validate((valid) => {
    if (valid) {
      save();
    } else {
      console.log("error submit!");
    }
  });
};

let handleClose = () => {
  orderId = "";
  info.value = {};
  model.value = {};
  emit("fatherMethod"); //列表重新加载
  dialogVisible.value = false;
};

watch(
  () => [model.value.city, model.value.district],
  (newValue, oldValue) => {
    model.value.enterpriseJurisdiction = `${model.value.city}${model.value.district}`;
  },
  { immediate: true, deep: true }
);

defineExpose({ open });
</script>


<style lang="scss">
.relationSelect {
  .el-select-dropdown__item {
    height: auto !important;
  }
  p {
    line-height: normal !important;
    height: auto !important;
  }
}
</style>

<style lang="scss" scoped>
.main {
  max-height: 70vh;
  overflow-y: auto;
}
</style>






